package cn.ecut.dzy.cf;

import java.util.concurrent.*;

/**
 * @program: juc
 * @description:
 * @author: DingZhenYun
 * @create: 2021-10-19 20:00
 **/

public class CompletableFutureDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 20, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
        //供给形接口
        CompletableFuture<Integer> integerCompletableFuture4 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "--come in");
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return 333;

        }).thenApply(f->{
            return f+2;
        }).whenCompleteAsync((v,e)->{
            if(e==null)
                System.out.println("----relust:"+v);
        }).exceptionally(e->{
            e.printStackTrace();
            return null;
        });
        System.out.println("--over111");

        //主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭:暂停3秒钟线程
        try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println("--22");

//        threadPoolExecutor.shutdown();
    }

    private static void m1() throws InterruptedException, ExecutionException {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(1, 20, 1L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(50), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        CompletableFuture<Void> voidCompletableFuture1 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "--come in");
        });
        System.out.println(voidCompletableFuture1.get());//null
        CompletableFuture<Void> voidCompletableFuture2 = CompletableFuture.runAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "--come in");
        }, threadPoolExecutor);

        //供给形接口
        CompletableFuture<Integer> integerCompletableFuture3 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "--come in");
            return 111;
        });
        System.out.println(integerCompletableFuture3.get());

        CompletableFuture<Integer> integerCompletableFuture4 = CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName() + "\t" + "--come in");
            return 333;
        },threadPoolExecutor);

        System.out.println(integerCompletableFuture4.get());

        threadPoolExecutor.shutdown();
    }
}
